package com.runfast.waimai.service.impl;

import com.runfast.common.service.BaseService;
import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import com.runfast.waimai.dao.mapper.RunfastActivityMapper;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.RunfastActivityService;
import com.runfast.waimai.service.RunfastBusinessService;
import com.runfast.waimai.service.RunfastGoodsSellRecordService;
import com.runfast.waimai.service.RunfastRedPacketRecordService;
import com.runfast.waimai.web.dto.ActivityDto;
import com.runfast.waimai.web.dto.TargetWithOneActivityDto;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Service
public class RunfastActivityServiceImpl extends BaseService<RunfastActivity, Integer, RunfastActivityExample> implements RunfastActivityService {

    @Autowired
    private RunfastGoodsSellRecordService orderService;

    @Autowired
    private RunfastRedPacketRecordService redPacketRecordService;

    @Autowired
    private RunfastBusinessService businessService;

    @Override
    public RunfastActivityMapper getMapper() {
        return (RunfastActivityMapper) super.getMapper();
    }


    @Override
    public List<RunfastActivity> getAgentZoneActivityIn(int agentId, List<Integer> activityTypeList) {
        return getMapper().getAgentZoneActivityIn(agentId, activityTypeList);
    }

    @Override
    public RunfastActivity getActivityWithTarget(Integer activityId, org.springframework.data.domain.Pageable pageable) {
        return getMapper().getActivityWithTarget(activityId, pageable);
    }

    @Override
    public List<TargetWithOneActivityDto> findBusinessActivity(Integer businessId, List<Integer> activityTypeList) {
        return getMapper().findBusinessActivity(businessId, activityTypeList);
    }


    /**
     * 领取红包
     *
     * @param redId
     * @param userId
     * @return
     */
    @Override
    public Result pick(Integer redId, Integer userId) {
        RunfastActivity activity = getMapper().get(redId);

        if (activity == null) return Result.fail(ResultCode.FAIL, "该红包活动不存在");

        Integer ptype = activity.getPtype();

        if (ptype != 10 && ptype != 12) return Result.fail(ResultCode.FAIL, "该红包活动不存在");

        if (ptype == 12) { //领取代理商红包
            Integer userType = activity.getRedUserType();
            userType = userType == null ? 0 : userType;
            if (userType == 1) { //近x日未下单用户
                Calendar todayStart = Calendar.getInstance();
                todayStart.set(Calendar.HOUR_OF_DAY, 0);
                todayStart.set(Calendar.MINUTE, 0);
                todayStart.set(Calendar.SECOND, 0);
                Integer day = activity.getRedDay();
                day = day == null ? 1 : day;
                Date start = todayStart.getTime();
                todayStart.set(Calendar.DAY_OF_MONTH, todayStart.get(Calendar.DAY_OF_MONTH) - day);
                Date end = todayStart.getTime();

                RunfastGoodsSellRecordExample goodsSellRecordExample = new RunfastGoodsSellRecordExample();
                goodsSellRecordExample.or().andUserIdEqualTo(userId).andCreateTimeBetween(start, end);
                List<RunfastGoodsSellRecord> goodsSellRecordList = orderService.selectByExample(goodsSellRecordExample);
                if (!goodsSellRecordList.isEmpty()) {
                    return Result.fail(ResultCode.FAIL, "您近" + day + "日下过单，不符合红包领取条件");
                }

            }
        }

        Integer activityId = activity.getId();

        Integer redLimitType = activity.getRedLimitType();
        redLimitType = redLimitType == null ? 0 : redLimitType;
        Integer redNum = activity.getRedNum();
        redNum = redNum == null ? 0 : redNum;
        if (redLimitType == 0) { //每天限量

            Integer redDayGet = activity.getRedDayGetNum();
            redDayGet = redDayGet == null ? 0 : redDayGet;

            Date redDayGetTime = activity.getRedDayGetTime();
            if (redDayGetTime != null) {//上一次有领取
                Calendar todayStart = Calendar.getInstance();
                todayStart.set(Calendar.HOUR_OF_DAY, 0);
                todayStart.set(Calendar.MINUTE, 0);
                todayStart.set(Calendar.SECOND, 0);

                if (redDayGetTime.before(todayStart.getTime())) {//上一次领取是在昨天,今天还没人领取，重置每日领取数据
                    RunfastActivity activityUpdate = new RunfastActivity();
                    activityUpdate.setId(activityId);
                    activityUpdate.setRedDayGetNum(1);
                    activityUpdate.setRedDayGetTime(new Date());

                    this.updateByPrimaryKeySelective(activityUpdate);

                    saveRedRecord(userId, activity);

                    return Result.ok("");
                } else {//上一次领取是在今天
                    if (redDayGet < redNum) {

                        return checkPersonLimit(userId, activity);
                    } else {
                        return Result.fail(ResultCode.FAIL, "今日的红包已经被领取完了,请明天再来");
                    }

                }

            } else {//上一次没有领取记录（无论昨日或今天）
                RunfastActivity activityUpdate = new RunfastActivity();
                activityUpdate.setId(activityId);
                activityUpdate.setRedDayGetNum(1);
                activityUpdate.setRedDayGetTime(new Date());

                this.updateByPrimaryKeySelective(activityUpdate);

                saveRedRecord(userId, activity);
                return Result.ok("");
            }


        } else {//总量限制
            Integer redGetNum = activity.getRedGetNum();
            redGetNum = redGetNum == null ? 0 : redGetNum;

            if (redGetNum < redNum) {
                return checkPersonLimit(userId, activity);
            } else {
                return Result.fail(ResultCode.FAIL, "红包已经被领取完了");
            }


        }
    }

    @Override
    public List<ActivityDto> findBusinessActivityDto(Integer businessId) {
        return getMapper().findBusinessActivityDto(businessId);
    }

    /**
     * 获取代理商下，用户可以领取的红包
     *
     * @param agentId
     * @param userId
     * @return
     */
    @Override
    public Result<List<RunfastActivity>> redActivityForPick(Integer agentId, Integer userId, Boolean random) {
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);

        List<RunfastActivity> redList = getMapper().findRedActivity(agentId);

        List<RunfastActivity> validRedList = new ArrayList<>();//可以领取的红包

        List<RunfastActivity> agentRedList = new ArrayList<>();
        List<RunfastActivity> businessRedList = new ArrayList<>();



        for (RunfastActivity activity : redList) {

            Integer activityId = activity.getId();
            Integer activityType = activity.getPtype();
            String activityName = activity.getName();
            Boolean shared = activity.getShared();
            Integer redValidDay = activity.getRedValidDay();
            Double fulls = activity.getFulls();
            String redAmount = activity.getRedAmount();
            Integer businessId = activity.getBusId();


            if (activityType == 10) { //商家红包才显示名称
                Map<String, Object> businessMap = businessService.findNameById(businessId);

                String businessName = (String) businessMap.get("name");

                activity.setBusname(businessName);

            }

            Integer userType = activity.getRedUserType();
            userType = userType == null ? 0 : userType;
            if (userType == 1) { //近x日未下单用户

                Integer day = activity.getRedDay();
                day = day == null ? 1 : day;
                Date start = todayStart.getTime();
                todayStart.set(Calendar.DAY_OF_MONTH, todayStart.get(Calendar.DAY_OF_MONTH) - day);
                Date end = todayStart.getTime();

                RunfastGoodsSellRecordExample goodsSellRecordExample = new RunfastGoodsSellRecordExample();
                goodsSellRecordExample.or().andUserIdEqualTo(userId).andCreateTimeBetween(start, end);
                List<RunfastGoodsSellRecord> goodsSellRecordList = orderService.selectByExample(goodsSellRecordExample);
                if (!goodsSellRecordList.isEmpty()) continue;

            }


            Integer redLimitType = activity.getRedLimitType();
            redLimitType = redLimitType == null ? 0 : redLimitType;
            Integer redNum = activity.getRedNum();
            redNum = redNum == null ? 0 : redNum;
            if (redLimitType == 0) { //每天限量

                Integer redDayGet = activity.getRedDayGetNum();
                redDayGet = redDayGet == null ? 0 : redDayGet;

                Date redDayGetTime = activity.getRedDayGetTime();
                if (redDayGetTime != null) {//上一次有领取

                    if (redDayGetTime.before(todayStart.getTime())) {//上一次领取是在昨天,今天还没人领取，重置每日领取数据

                        Integer i = getMapper().resetRedDay(activityId);

                        validRedList.add(activity);//显示红包
                    } else {//上一次领取是在今天
                        if (redDayGet < redNum) {

                            getValidRedListNoPicked(userId, validRedList, activity);
                        }

                    }


                } else {//上一次没有领取记录（无论昨日或今天）

                    validRedList.add(activity);//显示红包
                }


            } else {//总量限制
                Integer redGetNum = activity.getRedGetNum();
                redGetNum = redGetNum == null ? 0 : redGetNum;

                if (redGetNum < redNum) {
                    getValidRedListNoPicked(userId, validRedList, activity);
                }


            }


        }
        List<RunfastActivity> finalList = validRedList;

        if(random!=null&&random){
            finalList = new ArrayList<>();
            for (RunfastActivity activity : validRedList) {

                Integer activityType = activity.getPtype();
                if (activityType == 12) { //代理商创建的活动

                    agentRedList.add(activity);
                } else {
                    businessRedList.add(activity);

                }

            }


            if (agentRedList.size() >= 5) {

                finalList = agentRedList;
            } else {
                finalList.addAll(agentRedList);
                int remainSize = 5 - agentRedList.size();
                int businessSize = businessRedList.size();
                if(businessSize>0){


                    if(businessSize<= remainSize){

                        finalList.addAll(businessRedList);
                    }else{
                        HashSet<Integer> randomIndexSet = new HashSet<>();

                        while(randomIndexSet.size()<remainSize){
                            int index = RandomUtils.nextInt(0, businessSize);
                            randomIndexSet.add(index);
                        }

                        for (Integer index : randomIndexSet) finalList.add(businessRedList.get(index));

                    }


                }


            }
        }



        return Result.ok("", finalList);
    }

    private void getValidRedListNoPicked(Integer userId, List<RunfastActivity> validRedList, RunfastActivity activity) {


        Integer redPersonLimitType = activity.getRedPersonLimitType();
        redPersonLimitType = redPersonLimitType == null ? 0 : redPersonLimitType;
        if (redPersonLimitType == 0) {//每人1张
            RunfastRedPacketRecordExample redPacketRecordExample = new RunfastRedPacketRecordExample();
            redPacketRecordExample.or().andUserIdEqualTo(userId).andRedIdEqualTo(activity.getId());
            List<RunfastRedPacketRecord> redPacketRecordList = redPacketRecordService.selectByExample(redPacketRecordExample);
            if (redPacketRecordList.isEmpty()) {//还没有领取过该红包

                validRedList.add(activity);
            }

        } else {//每人每天1张
            RunfastRedPacketRecordExample redPacketRecordExample = new RunfastRedPacketRecordExample();

            Calendar todayStart = Calendar.getInstance();
            todayStart.set(Calendar.HOUR_OF_DAY, 0);
            todayStart.set(Calendar.MINUTE, 0);
            todayStart.set(Calendar.SECOND, 0);

            Date start = todayStart.getTime();
            todayStart.set(Calendar.DAY_OF_MONTH, todayStart.get(Calendar.DAY_OF_MONTH) + 1);
            Date end = todayStart.getTime();
            redPacketRecordExample.or().andUserIdEqualTo(userId).andRedIdEqualTo(activity.getId()).andCreateTimeBetween(start, end);
            List<RunfastRedPacketRecord> redPacketRecordList = redPacketRecordService.selectByExample(redPacketRecordExample);
            if (redPacketRecordList.isEmpty()) {//今天还没有领取过该红包

                validRedList.add(activity);
            }
        }
    }


    @Override
    public Result<List<RunfastActivity>> businessRedActivityForPick(Integer businessId, Integer userId ) {


        List<RunfastActivity> redList = getMapper().findBusinessRedActivity(businessId, 10); //获取商家红包

        List<RunfastActivity> validRedList = new ArrayList<>();//可以领取的红包

        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);


        List<RunfastActivity> agentRedList = new ArrayList<>();
        List<RunfastActivity> businessRedList = new ArrayList<>();
        for (RunfastActivity activity : redList) {

            Integer activityId = activity.getId();


            Integer redLimitType = activity.getRedLimitType();
            redLimitType = redLimitType == null ? 0 : redLimitType;
            Integer redNum = activity.getRedNum();
            redNum = redNum == null ? 0 : redNum;
            if (redLimitType == 0) { //每天限量

                Integer redDayGet = activity.getRedDayGetNum();
                redDayGet = redDayGet == null ? 0 : redDayGet;

                Date redDayGetTime = activity.getRedDayGetTime();
                if (redDayGetTime != null) {//上一次有领取

                    if (redDayGetTime.before(todayStart.getTime())) {//上一次领取是在昨天,今天还没人领取，重置每日领取数据
                        Integer i = getMapper().resetRedDay(activityId);

                        validRedList.add(activity);//显示红包
                    } else {//上一次领取是在今天
                        if (redDayGet < redNum) {

                            getValidRedList(userId, validRedList, activity);
                        }

                    }


                } else {//上一次没有领取记录（无论昨日或今天）

                    validRedList.add(activity);//显示红包
                }


            } else {//总量限制
                Integer redGetNum = activity.getRedGetNum();
                redGetNum = redGetNum == null ? 0 : redGetNum;

                if (redGetNum < redNum) {
                    getValidRedList(userId, validRedList, activity);
                }


            }





        }

        return Result.ok("", validRedList);
    }

    @Override
    public Result returnActivityForPick(int orderId, Integer userId) {

        RunfastGoodsSellRecord order = orderService.selectByPrimaryKey(orderId);
        if(order==null) return Result.fail(ResultCode.FAIL, "订单不存在");

        Integer status = order.getStatus();
        if(status!=RunfastGoodsSellRecord.Status.paid.getCode()) return Result.fail(ResultCode.FAIL, "支付后才能领取红包");

        BigDecimal totalpay = order.getTotalpay();

        Integer businessId = order.getBusinessId();


        List<RunfastActivity> redList = getMapper().findBusinessRedActivity(businessId, 11); //获取商家红包


        List<RunfastActivity> validRedList = new ArrayList<>();//可以领取的红包

        if(redList.isEmpty()) return Result.ok("", validRedList);


        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);


        List<RunfastActivity> agentRedList = new ArrayList<>();
        List<RunfastActivity> businessRedList = new ArrayList<>();
        for (RunfastActivity activity : redList) {

            Double fullReturn = activity.getFullReturn();
            if(fullReturn!=null&&totalpay.doubleValue() < fullReturn) continue; // 不满足赠送条件，跳过

            Integer activityId = activity.getId();

            Integer redLimitType = activity.getRedLimitType();
            redLimitType = redLimitType == null ? 0 : redLimitType;
            Integer redNum = activity.getRedNum();
            redNum = redNum == null ? 0 : redNum;
            if (redLimitType == 0) { //每天限量

                Integer redDayGet = activity.getRedDayGetNum();
                redDayGet = redDayGet == null ? 0 : redDayGet;

                Date redDayGetTime = activity.getRedDayGetTime();
                if (redDayGetTime != null) {//上一次有领取

                    if (redDayGetTime.before(todayStart.getTime())) {//上一次领取是在昨天,今天还没人领取，重置每日领取数据
                        Integer i = getMapper().resetRedDay(activityId);

                        validRedList.add(activity);//显示红包
                    } else {//上一次领取是在今天
                        if (redDayGet < redNum) {

                            getValidRedList(userId, validRedList, activity);
                        }

                    }


                } else {//上一次没有领取记录（无论昨日或今天）

                    validRedList.add(activity);//显示红包
                }


            } else {//总量限制
                Integer redGetNum = activity.getRedGetNum();
                redGetNum = redGetNum == null ? 0 : redGetNum;

                if (redGetNum < redNum) {
                    getValidRedList(userId, validRedList, activity);
                }


            }





        }

        return Result.ok("", validRedList);
    }


    private void getValidRedList(Integer userId, List<RunfastActivity> validRedList, RunfastActivity activity) {


        Integer redPersonLimitType = activity.getRedPersonLimitType();
        redPersonLimitType = redPersonLimitType == null ? 0 : redPersonLimitType;
        if (redPersonLimitType == 0) {//每人1张
            RunfastRedPacketRecordExample redPacketRecordExample = new RunfastRedPacketRecordExample();
            redPacketRecordExample.or().andUserIdEqualTo(userId).andRedIdEqualTo(activity.getId());
            List<RunfastRedPacketRecord> redPacketRecordList = redPacketRecordService.selectByExample(redPacketRecordExample);
            if (redPacketRecordList.isEmpty()) {//还没有领取过该红包

                validRedList.add(activity);
            }else{
                activity.setPicked(true);
                validRedList.add(activity);
            }

        } else {//每人每天1张
            RunfastRedPacketRecordExample redPacketRecordExample = new RunfastRedPacketRecordExample();

            Calendar todayStart = Calendar.getInstance();
            todayStart.set(Calendar.HOUR_OF_DAY, 0);
            todayStart.set(Calendar.MINUTE, 0);
            todayStart.set(Calendar.SECOND, 0);

            Date start = todayStart.getTime();
            todayStart.set(Calendar.DAY_OF_MONTH, todayStart.get(Calendar.DAY_OF_MONTH) + 1);
            Date end = todayStart.getTime();
            redPacketRecordExample.or().andUserIdEqualTo(userId).andRedIdEqualTo(activity.getId()).andCreateTimeBetween(start, end);
            List<RunfastRedPacketRecord> redPacketRecordList = redPacketRecordService.selectByExample(redPacketRecordExample);
            if (redPacketRecordList.isEmpty()) {//今天还没有领取过该红包

                validRedList.add(activity);
            }else{
                activity.setPicked(true);
                validRedList.add(activity);
            }
        }
    }


    private Result checkPersonLimit(Integer userId, RunfastActivity activity) {

        Integer redPersonLimitType = activity.getRedPersonLimitType();
        redPersonLimitType = redPersonLimitType == null ? 0 : redPersonLimitType;
        if (redPersonLimitType == 0) {//每人1张
            RunfastRedPacketRecordExample redPacketRecordExample = new RunfastRedPacketRecordExample();
            redPacketRecordExample.or().andUserIdEqualTo(userId).andRedIdEqualTo(activity.getId());
            List<RunfastRedPacketRecord> redPacketRecordList = redPacketRecordService.selectByExample(redPacketRecordExample);
            if (redPacketRecordList.isEmpty()) {//还没有领取过该红包

                saveRedRecord(userId, activity);
                return Result.ok("");
            } else {
                return Result.fail(ResultCode.FAIL, "已经领取过该红包，每人限量1个");
            }

        } else {//每人每天1张
            RunfastRedPacketRecordExample redPacketRecordExample = new RunfastRedPacketRecordExample();
            Calendar todayStart = Calendar.getInstance();
            todayStart.set(Calendar.HOUR_OF_DAY, 0);
            todayStart.set(Calendar.MINUTE, 0);
            todayStart.set(Calendar.SECOND, 0);

            Date start = todayStart.getTime();
            todayStart.set(Calendar.DAY_OF_MONTH, todayStart.get(Calendar.DAY_OF_MONTH) + 1);
            Date end = todayStart.getTime();
            redPacketRecordExample.or().andUserIdEqualTo(userId).andRedIdEqualTo(activity.getId()).andCreateTimeBetween(start, end);
            List<RunfastRedPacketRecord> redPacketRecordList = redPacketRecordService.selectByExample(redPacketRecordExample);
            if (redPacketRecordList.isEmpty()) {

                saveRedRecord(userId, activity);
                return Result.ok("");
            } else {

                return Result.fail(ResultCode.FAIL, "今天已经领取过该红包，每人每天限量1个");
            }
        }


    }

    private void saveRedRecord(Integer userId, RunfastActivity activity) {
        RunfastRedPacketRecord redPacketRecord = new RunfastRedPacketRecord();

        Calendar now = Calendar.getInstance();
        redPacketRecord.setCreateTime(now.getTime());
        redPacketRecord.setRedId(activity.getId());
        redPacketRecord.setUserId(userId);
        redPacketRecord.setUsed(false);
        redPacketRecord.setFull(activity.getFulls());

        String redAmount = activity.getRedAmount();
        String[] split = redAmount.split(",");
        Double less = 0d;
        if (split.length > 1) {//随机金额
            double nextDouble = RandomUtils.nextDouble(Double.valueOf(split[0]), Double.valueOf(split[0]));
            BigDecimal bigDecimal = BigDecimal.valueOf(nextDouble).setScale(2, RoundingMode.FLOOR);
            less = bigDecimal.doubleValue();

        } else { //固定金额
            if (StringUtils.isNotBlank(split[0])) {
                less = Double.valueOf(split[0]);
            }

        }
        redPacketRecord.setLess(less);

        Integer redValidDay = activity.getRedValidDay();
        redValidDay = redValidDay==null?1:redValidDay;
        now.add(Calendar.DAY_OF_MONTH, redValidDay);
        redPacketRecord.setEndTime(now.getTime());
        redPacketRecordService.insert(redPacketRecord);
    }


}